<script setup>
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import api from '@/api'
import { Message } from '@arco-design/web-vue'

const $route = useRoute()
const $router = useRouter()

const productList = ref([])
const currentDepartmentIndex = ref(0)
const currentPositionIndex = ref(0)
const departmentList = ref([])
const positionList = ref([])
const postsOptionList = ref([])
const listData = ref() // 员工列表
const keyword = ref('')
const pageVal = ref(1)
const pageSize = ref(10)
const listTotal = ref(0)
const listLoading = ref(false)
const formData = ref({
  id: null,
  name: '',
  username: '',
  password: '',
  post_id: '',
}) // 员工表单
const formVisible = ref(false) // 员工管理弹窗
const formDataDepartment = ref({
  id: null,
  name: '',
  permission_id: [],
  data_divide: [],
}) // 部门表单
const formVisibleDepartment = ref(false) // 部门管理弹窗
const formDataPosts = ref({
  id: null,
  name: '',
  department_id: null,
  permission_id: [],
  data_divide: [],
}) // 岗位表单
const formVisiblePosts = ref(false) // 岗位管理弹窗

const getMenuAllList = async () => {
  try {
    const res = await api.get('system/menuAllList')
    console.log('res', res)
    productList.value = res.data
  } catch (error) {
    console.error('error', error)
    return false
  }
}
const handleChangePermissionIdDepartment = async (e) => {
  // 取交集
  formDataDepartment.value.data_divide =
    formDataDepartment.value.permission_id.filter((item) =>
      formDataDepartment.value.data_divide.includes(item)
    )
}
const handleChangeDataDivideDepartment = async (e) => {
  // 取并集
  formDataDepartment.value.permission_id = [
    ...new Set([...formDataDepartment.value.permission_id, ...e]),
  ]
}
// 删除部门
const deleteItemDepartment = async (id) => {
  try {
    const res = await api.get('system/delDepartment/' + id)
    Message.success(res.message)
    window.location.reload()
  } catch (error) {
    console.error('error', error)
    return false
  }
}
// 显示部门表单
const showFormDataDepartment = async (record) => {
  if (record) {
    formDataDepartment.value.id = record.id
    formDataDepartment.value.name = record.name
    formDataDepartment.value.permission_id = record.permission_id
      ? record.permission_id.split(',').map((e) => e * 1)
      : []
    formDataDepartment.value.data_divide = record.data_divide
      ? record.data_divide.split(',').map((e) => e * 1)
      : []
  } else {
    resetFormDataDepartment()
  }
  formVisibleDepartment.value = true
}
// 提交部门表单
const formSubmitDepartment = async () => {
  console.log('formDataDepartment', formDataDepartment.value)
  var obj = { ...formDataDepartment.value }
  obj.permission_id = obj.permission_id.toString()
  obj.data_divide = obj.data_divide.toString()
  if (!obj.name) {
    Message.error('部门名称不可为空')
    return false
  }
  if (obj.id) {
    try {
      const res = await api.post('system/updateDepartment', obj)
      Message.success(res.message)
      formVisibleDepartment.value = false
      getDepartmentList()
      resetFormDataDepartment()
    } catch (error) {
      console.error('error', error)
      return false
    }
  } else {
    try {
      const res = await api.post('system/createDepartment', obj)
      Message.success(res.message)
      formVisibleDepartment.value = false
      getDepartmentList()
      resetFormDataDepartment()
    } catch (error) {
      console.error('error', error)
      return false
    }
  }
}
// 重置部门表单
const resetFormDataDepartment = async () => {
  formDataDepartment.value = {
    id: null,
    name: '',
    permission_id: [],
    data_divide: [],
  }
}

const deleteItemPosts = async (id) => {
  try {
    const res = await api.get('system/delPosts/' + id)
    Message.success(res.message)
    window.location.reload()
  } catch (error) {
    console.error('error', error)
    return false
  }
}

const showFormDataPosts = async (record) => {
  if (record) {
    formDataPosts.value.id = record.id
    formDataPosts.value.name = record.name
    formDataPosts.value.department_id = record.department_id
    formDataPosts.value.permission_id = record.permission_id
      ? record.permission_id.split(',').map((e) => e * 1)
      : []
    formDataPosts.value.data_divide = record.data_divide
      ? record.data_divide.split(',').map((e) => e * 1)
      : []
  } else {
    resetFormDataPosts()
  }
  formVisiblePosts.value = true
} // 显示部门表单

const formSubmitPosts = async () => {
  console.log('formDataPosts', formDataPosts.value)
  var obj = { ...formDataPosts.value }
  obj.permission_id = obj.permission_id.toString()
  obj.data_divide = obj.data_divide.toString()
  if (!obj.name) {
    Message.error('岗位名称不可为空')
    return false
  }
  if (!obj.department_id) {
    Message.error('所属部门不可为空')
    return false
  }
  if (obj.id) {
    try {
      const res = await api.post('system/updatePosts', obj)
      Message.success(res.message)
      formVisiblePosts.value = false
      getPositionList()
      getPostsOptions()
      resetFormDataPosts()
    } catch (error) {
      console.error('error', error)
      return false
    }
  } else {
    try {
      const res = await api.post('system/createPosts', obj)
      Message.success(res.message)
      formVisiblePosts.value = false
      getPositionList()
      getPostsOptions()
      resetFormDataPosts()
    } catch (error) {
      console.error('error', error)
      return false
    }
  }
} // 提交员工表单

const resetFormDataPosts = async () => {
  formDataPosts.value = {
    id: null,
    name: '',
    department_id: departmentList.value[currentDepartmentIndex.value].id,
    permission_id: [],
    data_divide: [],
  }
}

const handleChangePermissionIdPosts = async (e) => {
  // 取交集
  formDataPosts.value.data_divide = formDataPosts.value.permission_id.filter(
    (item) => formDataPosts.value.data_divide.includes(item)
  )
}

const handleChangeDataDividePosts = async (e) => {
  // 取并集
  formDataPosts.value.permission_id = [
    ...new Set([...formDataPosts.value.permission_id, ...e]),
  ]
}

// 获取员工列表
const getListData = async (page) => {
  listLoading.value = true
  try {
    const res = await api.get('system/userList', {
      params: {
        keyword: keyword.value,
        department_id: departmentList.value[currentDepartmentIndex.value].id,
        post_id: positionList.value[currentPositionIndex.value].id,
        page,
        pageSize: pageSize.value,
      },
    })
    console.log('res', res)
    listData.value = res.data.items
    listTotal.value = res.data.pageInfo.total
    pageVal.value = page
  } catch (error) {
    console.error(error)
  }
  listLoading.value = false
}
// 获取部门列表
const getDepartmentList = async () => {
  try {
    const res = await api.get('system/departmentOptions')
    console.log('res', res)
    departmentList.value = res.data

    if (res.data.length) {
      getPositionList()
    }
  } catch (error) {
    console.error('error', error)
    return false
  }
}
// 获取部门下的岗位列表
const getPositionList = async () => {
  try {
    const res = await api.get(
      'system/postAllList/' +
        departmentList.value[currentDepartmentIndex.value].id
    )
    console.log('res', res)
    positionList.value = res.data

    if (res.data.length) {
      getListData(1)
    }
  } catch (error) {
    console.error('error', error)
    return false
  }
}
// 获取岗位部门组合式列表
const getPostsOptions = async () => {
  try {
    const res = await api.get('system/postsOptions')
    console.log('res', res)
    postsOptionList.value = res.data
  } catch (error) {
    console.error('error', error)
    return false
  }
}
// 选择部门
const changeDepartmentIndex = async (index) => {
  listData.value = []
  listTotal.value = 0
  currentDepartmentIndex.value = index
  currentPositionIndex.value = 0
  getPositionList()
}
// 选择岗位
const changePositionIndex = async (index) => {
  listData.value = []
  listTotal.value = 0
  currentPositionIndex.value = index
  getListData()
}
// 显示员工表单
const showFormData = async (record) => {
  if (record) {
    formData.value.id = record.id
    formData.value.name = record.name
    formData.value.username = record.username
    formData.value.post_id = record.postsall[0].id
  } else {
    resetFormData()
  }
  formVisible.value = true
}
// 提交员工表单
const formSubmit = async () => {
  console.log('formSubmit', formData.value)
  if (!formData.value.name) {
    Message.error('姓名不可为空')
    return false
  }
  if (!formData.value.username) {
    Message.error('账号/手机号不可为空')
    return false
  }
  if (!formData.value.post_id) {
    Message.error('岗位不可为空')
    return false
  }
  // if (!formData.value.password) {
  //   Message.error('密码不可为空')
  //   return false
  // }
  if (formData.value.id) {
    try {
      const res = await api.post(
        'system/updateUser/' + formData.value.id,
        formData.value
      )
      Message.success(res.message)
      getListData(1)
      resetFormData()
    } catch (error) {
      console.error('error', error)
      return false
    }
  } else {
    try {
      const res = await api.post('system/createUser', formData.value)
      Message.success(res.message)
      getListData(1)
      resetFormData()
    } catch (error) {
      console.error('error', error)
      return false
    }
  }
}
// 重置员工表单
const resetFormData = async () => {
  formData.value = {
    id: null,
    name: '',
    username: '',
    password: '',
    post_id: (formData.value.post_id =
      positionList.value[currentPositionIndex.value].id),
  }
}
// 删除员工
const deleteItem = async (id) => {
  try {
    const res = await api.get('system/delUser/' + id)
    Message.success(res.message)
    getListData(1)
  } catch (error) {
    console.error('error', error)
    return false
  }
}

getDepartmentList()
getPostsOptions()
getMenuAllList()
</script>

<template>
  <div class="page">
    <div class="header">
      <a-space>
        <a-input :style="{ width: '240px' }"
                 v-model="keyword"
                 placeholder="按账号/手机号查询"
                 allow-clear />

        <a-button @click="getListData(1)"
                  type="primary">查询</a-button>
      </a-space>
      <a-button @click="showFormData()"
                type="primary">添加员工</a-button>
    </div>

    <div class="talent_body">
      <div class="switch_category">
        <div class="switch_category_div">
          <div class="name">
            <span class="mr10">部门</span>
            <a-button @click="showFormDataDepartment()"
                      type="outline"
                      size="mini">
              <template #icon>
                <icon-plus />
              </template>
            </a-button>
          </div>
          <div class="category_list">
            <div @click="changeDepartmentIndex(index)"
                 class="category_cell"
                 :class="{active: currentDepartmentIndex==index}"
                 v-for="(item,index) in departmentList"
                 :key="index">
              <span class="mr10">{{ item.name }}</span>
              <a-button @click.stop="showFormDataDepartment(item)"
                        v-if="currentDepartmentIndex==index"
                        type="dashed"
                        size="mini"
                        shape="circle">
                <template #icon>
                  <icon-edit />
                </template>
              </a-button>

              <a-button @click.stop="showFormDataDepartment(item)"
                        v-else
                        type="outline"
                        size="mini"
                        shape="circle">
                <template #icon>
                  <icon-edit />
                </template>
              </a-button>
            </div>
          </div>
        </div>
        <div class="switch_category_div">
          <div class="name">
            <span class="mr10">岗位</span>
            <a-button @click="showFormDataPosts()"
                      type="outline"
                      size="mini">
              <template #icon>
                <icon-plus />
              </template>
            </a-button>
          </div>
          <div>
            <div @click="changePositionIndex(index)"
                 class="category_cell"
                 :class="{active: currentPositionIndex==index}"
                 v-for="(item,index) in positionList"
                 :key="index">
              <span class="mr10">{{ item.name }}</span>
              <a-button @click.stop="showFormDataPosts(item)"
                        v-if="currentPositionIndex==index"
                        type="dashed"
                        size="mini"
                        shape="circle">
                <template #icon>
                  <icon-edit />
                </template>
              </a-button>

              <a-button @click.stop="showFormDataPosts(item)"
                        v-else
                        type="outline"
                        size="mini"
                        shape="circle">
                <template #icon>
                  <icon-edit />
                </template>
              </a-button>
            </div>
          </div>
        </div>
      </div>
      <div class="talent_table">
        <a-table :data="listData"
                 @page-change="getListData"
                 :pagination="{
                  showTotal: true,
                  size: 'small',
                  total: listTotal,
                  pageSize: pageSize,
                  current: pageVal,
                }">
          <template #columns>
            <a-table-column title="序号"
                            :width="60">
              <template #cell="{ rowIndex }"> {{ rowIndex + 1 }} </template>
            </a-table-column>
            <a-table-column title="姓名"
                            data-index="name"></a-table-column>
            <a-table-column title="账号/手机号"
                            data-index="username"></a-table-column>
            <a-table-column title="部门">
              <template #cell="{ record }">
                {{ record.postsall[0].department.name }}
              </template>
            </a-table-column>
            <a-table-column title="岗位">
              <template #cell="{ record }">
                {{ record.postsall[0].name }}
              </template>
            </a-table-column>
            <a-table-column title="添加时间"
                            data-index="created_at"></a-table-column>
            <a-table-column title="操作"
                            align="center"
                            :width="300">
              <template #cell="{ record }">
                <a-space>
                  <a-popconfirm @ok="deleteItem(record.id)"
                                content="确认删除该数据吗?"
                                type="warning">
                    <a-button type="primary"
                              status="danger"
                              size="mini">删除</a-button>
                  </a-popconfirm>
                  <a-button @click="showFormData(record)"
                            type="primary"
                            size="mini">编辑</a-button>
                </a-space>
              </template>
            </a-table-column>
          </template>
        </a-table>

        <a-modal :title="formData.id ? '编辑员工':'添加员工'"
                 width="600px"
                 :on-before-ok="formSubmit"
                 v-model:visible="formVisible">
          <a-form>
            <a-form-item label="姓名">
              <a-input :style="{width:'400px'}"
                       v-model="formData.name"
                       placeholder="请输入姓名"
                       allow-clear></a-input>
            </a-form-item>
            <a-form-item label="账号/手机号">
              <a-input :style="{width:'400px'}"
                       v-model="formData.username"
                       placeholder="请输入账号/手机号"
                       allow-clear></a-input>
            </a-form-item>
            <a-form-item label="岗位">
              <a-select v-model="formData.post_id"
                        :style="{width:'400px'}"
                        placeholder="请选择岗位">
                <a-optgroup :label="item.name"
                            v-for="(item,index) in postsOptionList"
                            :key="index">
                  <a-option :value="items.id"
                            v-for="(items,indexs) in item.posts"
                            :key="indexs">
                    {{ items.name }}
                  </a-option>
                </a-optgroup>
              </a-select>
            </a-form-item>
            <a-form-item label="密码">
              <a-input :style="{width:'400px'}"
                       v-model="formData.password"
                       :placeholder="formData.id ? '不输入则为不修改密码' : '请输入密码'"
                       allow-clear></a-input>
            </a-form-item>
          </a-form>
        </a-modal>
      </div>
    </div>

    <a-modal :title="formDataDepartment.id ? '编辑部门':'添加部门'"
             width="600px"
             :on-before-ok="formSubmitDepartment"
             v-model:visible="formVisibleDepartment">
      <a-form>
        <a-form-item label="部门名称">
          <a-input :style="{width:'400px'}"
                   v-model="formDataDepartment.name"
                   placeholder="请输入部门名称"
                   maxlength="6"
                   allow-clear></a-input>
        </a-form-item>
        <a-form-item label="权限">
          <a-checkbox-group v-model="formDataDepartment.permission_id"
                            @change="handleChangePermissionIdDepartment">
            <a-checkbox v-for="(item,index) in productList"
                        :key="index"
                        :value="item.id">{{ item.title }}</a-checkbox>
          </a-checkbox-group>
        </a-form-item>
        <a-form-item label="数据隔离">
          <a-checkbox-group v-model="formDataDepartment.data_divide"
                            @change="handleChangeDataDivideDepartment">
            <a-checkbox v-for="(item,index) in productList"
                        :key="index"
                        :value="item.id">{{ item.title }}</a-checkbox>
          </a-checkbox-group>
        </a-form-item>
      </a-form>
      <template #footer>
        <div class="flex at_c jc_b fd_rr">
          <a-space>
            <a-button @click="formVisibleDepartment = false">取消</a-button>
            <a-button type="primary"
                      @click="formSubmitDepartment">确定</a-button>
          </a-space>
          <a-popconfirm v-if="formDataDepartment.id"
                        @ok="deleteItemDepartment(formDataDepartment.id)"
                        content="确认删除该数据吗?"
                        type="warning">
            <a-button type="primary"
                      status="danger">删除</a-button>
          </a-popconfirm>
        </div>
      </template>
    </a-modal>

    <a-modal :title="formDataPosts.id ? '编辑岗位':'添加岗位'"
             width="600px"
             :on-before-ok="formSubmitPosts"
             v-model:visible="formVisiblePosts">
      <a-form>
        <a-form-item label="岗位名称">
          <a-input :style="{width:'400px'}"
                   v-model="formDataPosts.name"
                   placeholder="请输入岗位名称"
                   maxlength="6"
                   allow-clear></a-input>
        </a-form-item>
        <a-form-item label="所属部门">
          <a-select v-model="formDataPosts.department_id"
                    :style="{width:'400px'}"
                    placeholder="请选择所属部门">
            <a-option v-for="(item,index) in departmentList"
                      :key="index"
                      :value="item.id">{{item.name}}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="权限">
          <a-checkbox-group v-model="formDataPosts.permission_id"
                            @change="handleChangePermissionIdPosts">
            <a-checkbox v-for="(item,index) in productList"
                        :key="index"
                        :value="item.id">{{ item.title }}</a-checkbox>
          </a-checkbox-group>
        </a-form-item>
        <a-form-item label="数据隔离">
          <a-checkbox-group v-model="formDataPosts.data_divide"
                            @change="handleChangeDataDividePosts">
            <a-checkbox v-for="(item,index) in productList"
                        :key="index"
                        :value="item.id">{{ item.title }}</a-checkbox>
          </a-checkbox-group>
        </a-form-item>
      </a-form>
      <template #footer>
        <div class="flex at_c jc_b fd_rr">
          <a-space>
            <a-button @click="formVisiblePosts = false">取消</a-button>
            <a-button type="primary"
                      @click="formSubmitPosts">确定</a-button>
          </a-space>
          <a-popconfirm v-if="formDataPosts.id"
                        @ok="deleteItemPosts(formDataPosts.id)"
                        content="确认删除该数据吗?"
                        type="warning">
            <a-button type="primary"
                      status="danger">删除</a-button>
          </a-popconfirm>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<style scoped>
.page {
  height: 100%;
}

.header {
  height: 52px;
  display: flex;
  justify-content: space-between;
}

.talent_body {
  width: 100%;
  height: calc(100% - 52px);
  display: flex;
}

.switch_category {
  width: 400px;
  display: flex;
}

.switch_category_div {
  flex: 1;
  background: #ffffff;
  box-sizing: border-box;
  border-top: 1px solid #e5e6eb;
}

.switch_category_div:not(:last-child) {
  border-right: 1px solid #e5e6eb;
}

.switch_category_div .name {
  background-color: #f2f3f5;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.switch_category_div .category_list {
  height: calc(100% - 40px);
  overflow-y: auto;
}

.switch_category_div .category_cell {
  cursor: pointer;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.switch_category_div .active {
  background-color: #165dff;
  color: #fff;
}

.talent_table {
  width: calc(100% - 400px);
}

.fd_rr {
  flex-direction: row-reverse;
}
</style>